function Copy-Tables
(
	[system.string]$sourceDatabase = $(throw "'sourceDatabase' Specify the database to copy tables from."),
	[system.string]$targetDatabase = $(throw "'targetDatabase' Specify the database to copy tables to."),
	[system.string]$whereClause = $(throw "'whereClause' Specify the sys.objects filter that specifies which objects to copy."),
	[switch]$createTargetDatabase,
	[switch]$whatIf
)
{
	$ErrorActionPreference  = "Continue"
	
	if ($sourceDatabase -eq $targetDatabase)
	{
		write-error "Target database cannot be the same as the source."
		return;
	}
	
	$checkDatabaseExistsCommand = "SELECT 1 FROM sys.databases WHERE name = '{0}'" -f $targetDatabase
	$databaseExists = invoke-sqlcmd -query $checkDatabaseExistsCommand
	
	if ($createTargetDatabase -eq $true)
	{
		if ($databaseExists -ne $null)
		{
			write-host "The database $targetDatabase already exists and will be used." -foregroundcolor cyan
		}
		else
		{
			$createDatabaseCommand = "CREATE DATABASE [{0}];" -f $targetDatabase
			
			if ($whatIf -eq $true)
			{
				write-host "The database $targetDatabase will be created."
			}
			else
			{
				invoke-sqlcmd -query $createDatabaseCommand
			}
		}
	}

	$objectQuery = "SELECT name as object_name, SCHEMA_NAME(schema_id) as schema_name FROM [{0}].sys.objects WHERE {1};" -f $sourceDatabase, $whereClause
	$objectsToCopy = invoke-sqlcmd -query $objectQuery

	
	foreach ($dataRow in $objectsToCopy)
	{
		$sourceObject = "[{0}].[{1}].[{2}]" -f $sourceDatabase, $dataRow["schema_name"], $dataRow["object_name"]
		$destinationObject = "[{0}].[{1}].[{2}]" -f $targetDatabase, $dataRow["schema_name"], $dataRow["object_name"]
		$schemaName = $dataRow["schema_name"]
		$checkSchemaExistsCommand = "SELECT 1 FROM [{0}].sys.schemas WHERE name = '{1}'" -f $targetDatabase, $schemaName
		$schemas = invoke-sqlcmd -query $checkSchemaExistsCommand
		
		if ($schemas -eq $null)
		{
			if ($whatIf -eq $true)
			{
				write-host "The schema $schemaName will be created." -foregroundcolor cyan
			}
			else
			{
				$createSchemaCommand = "CREATE SCHEMA [{1}];" -f $targetDatabase, $schemaName
				invoke-sqlcmd -database $targetDatabase -query $createSchemaCommand
			}
		}
		
		if ($whatIf -eq $true)
		{
			write-host "Data will be copied from $sourceObject to $destinationObject" -foregroundcolor cyan
		}
		else
		{
			write-host "Copying data from $sourceObject to $destinationObject" -foregroundcolor cyan
			$copyCommand = "SELECT * INTO {0} FROM {1}" -f $destinationObject, $sourceObject
			invoke-sqlcmd -query $copyCommand
		}
	}	
}